<?php if(!defined('MS_XTIGER')) exit('Access Denied');
/**
 * Created by openXtiger.org
 * User: xtiger
 * Date: 2009-5-31
 * Time: 10:11:25
 */

 function xtb_module_add() {
    return 'editmodule';
 }
 
 function xtb_module_update($m="") {
    global $xtb_modules;
    if(array_key_exists($m,$xtb_modules)) {
        xt_set('name',$m);
        xt_set('path',$xtb_modules[$m]['modulePath']);
    }
    return 'editmodule';
 }
 
 function xtb_module_save() {
    global $xtb_modules;
    $name = trim($_POST['name']);

    if(empty($name)){
        xt_set('msg','please input name!');
        return 'editmodule';
    }
    $path = str_replace('\\','/',$_POST['path']);
    if(empty($path)){
        xt_set('msg','please input path!');
        return 'editmodule';
    }
    
    substr($path,-1) != '/' && $path.='/';

    if(array_key_exists($name,$xtb_modules)) {
        $xtb_modules[$name]['modulePath']=$path;
    } else {
        $xtb_modules[$name] = array('modulePath'=>$path);
    }
    $s = "\$xtb_modules = array();\n";
    foreach($xtb_modules as $k => $v) {
        $s .= "\$xtb_modules['$k']="._xtc_implode($v,0).";\n";
    }
    xt_writefile(MS_CACHEPATH.'./RuntimeModules.cache.php', $s, 'php', 'w', 0);
    return xt_redirect();
 }
 
 function xtb_module_list($m="") {
    global $xtb_modules;
    if(empty($m)) return NONE;
    $p = '';$pp='';
    if(func_num_args() > 2) {
        $c = func_num_args()-3;
        $p = implode(array_slice(func_get_args(),2),'/').'/';
        $pp = implode(array_slice(func_get_args(),2,$c),'/');
    }
    echo  '<strong>'.$m.'/'.$p.'</strong>&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.xt_uri('','').'">Choose modules</a>';
    echo  '&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.xt_uri('/module/update/'.$m).'">update module</a>';
    echo  '&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.xt_uri('/compiler/views/'.$m).'">Compile views</a><hr/>';
    echo "\n<table style=\"border:1px\" width=\"100%\">";
    echo "\n<tr><th width=\"33%\">local path</th><th width=\"33%\">result path</th><th width=\"33%\">action path</th></tr>\n";
    $module = $xtb_modules[$m];
    if(empty($module)) return NONE;

    $dir = $module['modulePath'].'.static/'.$p;
    $dirs = array();
    foreach(scandir($dir) as $file) {
        if(is_dir($dir.$file) && $file !='.' && $file !='..') {
            $dirs[] = '<tr><td colspan=\"3\"><a href="'.xt_uri('/module/list/'.$m.'/'.$p.$file).'">'.$p.$file.'</a></td></tr>';
            continue;
        }
        if(preg_match("/(.*)\.html$/",$file,$ff)){
            echo "<tr><td>$p$ff[1]</td><td> </td><td> </td></tr>\n";
        }
    }
    echo "<tr><td colspan=\"3\" height=\"2\" bgcolor=\"#cccccc\"></td></tr>\n";
    echo '<tr><td colspan="3"><a href="'.xt_uri('/module/list/'.$m.'/'.$pp).'">Parent Dirs</a></td></tr>';
    foreach($dirs as $d) {
        echo $d;
    }
    echo '</table>';
    return NONE;
 }
?>